<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    :close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="70px" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="dialogTitle === '添加用户'">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from 'vue'
import { addUser, editUser } from '@/api/users'
import { ElMessage } from 'element-plus'
// 使用自己定义的i18n
import i18n from '@/i18n'

// 导入父传子的内容
const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTitleValue: {
    type: Object,
    default: () => {}
  }
})

// 表单内容
const formRef = ref(null)
const form = ref({
  username: '',
  password: '',
  email: '',
  mobile: ''
})
// 表单校验
const rules = ref({
  username: [{ required: true, message: '用户名错误', trigger: 'blur' }],
  password: [
    { required: true, message: '密码错误', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/,
      message: '至少8-16个字符，包含任意1个大小写字母'
    }
  ],
  email: [
    { required: true, message: '邮箱错误', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    { required: true, message: '电话错误', trigger: 'blur' },
    {
      pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
      message: '请输入正确的手机号码'
    }
  ]
})

watch(
  () => props.dialogTitleValue,
  () => {
    // console.log(props.dialogTitleValue)
    form.value = props.dialogTitleValue
  },
  { deep: true, immediate: true }
)
// 因为可能会有很多方法，所以是数组,用法model-value要改成大小写
const emits = defineEmits(['update:modelValue', 'initUserList'])
// 然后点击事件发送false关闭弹窗
const handleClose = () => {
  emits('update:modelValue', false)
}

// 点击确认事件中调用addUser传递，表单内容
const handleConfirm = () => {
  // 表单校验
  formRef.value.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加用户' ? await addUser(form.value) : await editUser(form.value)
      ElMessage({
        message: i18n.global.t('message.updeteSuccess'),
        type: 'success'
      })
      emits('initUserList')
      handleClose()
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

</script>
<style lang="scss" scoped></style>
